import sys
import xmindparser
import xlwt
import testcase
import csv
import xlrd

def Transfer(file, output_xls, output_csv):
    testcases = xmindparser.xmind_to_dict(file)[0]['topic']
    workbook = xlwt.Workbook(encoding='UTF-8')
    worksheet = workbook.add_sheet(testcases['title'], cell_overwrite_ok=True)
    row0 = ['Test Case Identifier', 'Priority', 'Summary', 'Pre-Conditions', 'Data', 'Action', 'Expected Result',
            'Labels', 'Test Repository Path']
    for i in range(len(row0)):
        worksheet.write(0, i, row0[i])

    lst = []
    r_s = testcases['title']
    process_dict(testcases, r_s, lst)
    dct = {}
    tc_lst = process_list(lst, dct, worksheet)
    dump_tc_lst(tc_lst, worksheet)
    workbook.save(output_xls)
    convert_xls_to_csv(output_xls, output_csv)

def process_dict(root, rootstring, list_container):
    if isinstance(root, dict):
        if len(root) >= 2 and 'topics' in root.keys():
            process_dict(root['topics'], str(rootstring), list_container)
        if len(root) == 1:
            process_dict(root['title'], str(rootstring), list_container)
    elif isinstance(root, list):
        for dec_root in root:
            process_dict(dec_root, str(rootstring) + "###" + dec_root['title'], list_container)
    elif isinstance(root, str):
        list_container.append(str(rootstring))

def process_list(lst, content: list, worksheet):
    tc_list = []
    for rec in lst:
        rec = rec.replace('：', ':')
        tc = testcase.test_case()
        parts = rec.split('###')
        repositorypath = ''
        for i in range(len(parts)):
            if parts[i].startswith('tc'):
                break
            else:
                repositorypath = repositorypath + '/' + parts[i]
        for seg in parts:
            if 'tc' in seg:
                title = seg.split(':')[1]
                idx = check(tc_list, title)
                if idx == -1:
                    tc.title = title
                    tc.repositoryPath = repositorypath
                    tc_list.append(tc)
                else:
                    tc = tc_list[idx]
                i = parts.index(seg)
                if len(parts) - i > 1:
                    step = parts[i + 1]
                    if 'pc' in step:
                        condition = step.split(':')[1]
                        tc.condition = condition
                    else:
                        tst_step = testcase.test_step()
                        tst_step.title = step
                        exp = ' '
                        if len(parts) - i > 3:
                            exp = parts[i + 2]
                            data = parts[i + 3]
                            tst_step.dataed.append(data)
                        elif len(parts) - i > 2:
                            exp = parts[i + 2]
                        tst_step.expected.append(exp)
                        tc.apptend_step(tst_step)
    return tc_list

def dump_tc_lst(tc_lst, worksheet):
    l = 1
    for tc in tc_lst:
        idx = tc_lst.index(tc) + 1
        worksheet.write(l, 1, priority)
        worksheet.write(l, 2, tc.title)
        worksheet.write(l, 3, tc.condition)
        worksheet.write(l, 7, label1)
        worksheet.write(l, 8, tc.repositoryPath)
        data_str = ''
        exp_str = ''
        for step in tc.steps:
            worksheet.write(l, 0, idx)
            worksheet.write(l, 5, step.title)
            for exp in step.expected:
                if exp_str == '':
                    exp_str = str(exp)
                else:
                    exp_str = exp_str + '; ' + str(exp)
            worksheet.write(l, 6, exp_str)
            exp_str = ''
            for data in step.dataed:
                if data_str == '':
                    data_str = str(data)
                else:
                    data_str = data_str + '; ' + str(data)
            worksheet.write(l, 4, data_str)
            data_str = ''
            l = l + 1

def check(lst, title):
    for case in lst:
        if case.title == title:
            return lst.index(case)
    return -1


def convert_xls_to_csv(xls_file, csv_file):
    workbook = xlrd.open_workbook(xls_file)
    sheet = workbook.sheet_by_index(0)
    with open(csv_file, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for row_idx in range(sheet.nrows):
            writer.writerow(sheet.row_values(row_idx))


if __name__ == '__main__':
    priority = 'Medium'
    label1 = ''
    if len(sys.argv) < 2:
        print("请至少提供一个参数。")
        sys.exit(1)
    file_name = sys.argv[1][:-6]
    xmind_file = file_name + '.xmind'
    exl_output = file_name + '.xls'
    csv_output = file_name + '.csv'
    Transfer(xmind_file, exl_output, csv_output)